<!DOCTYPE html>
<html>
<head>
    <title>Advanced AI Chat Interface</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- External Dependencies -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/9.1.6/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-bash.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-yaml.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/mermaid@10.6.1/dist/mermaid.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
    <style>
        /* Previous styles remain the same */
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            height: 100vh;
            display: flex;
            background: #f0f2f5;
        }

        .sidebar {
            width: 250px;
            background: #2d3748;
            padding: 20px;
            color: white;
            height: 100vh;
            overflow-y: auto;
            position: fixed;
            left: 0;
            top: 0;
            box-sizing: border-box;
        }

        .main-content {
            margin-left: 250px;
            flex: 1;
            padding: 20px;
            box-sizing: border-box;
            width: calc(100% - 250px);
        }

        .chat-container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            height: calc(100vh - 40px);
        }

        .chat-header {
            background: #2d3748;
            color: white;
            padding: 15px;
            border-radius: 10px 10px 0 0;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }

        .chat-input {
            padding: 20px;
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
            display: flex;
            gap: 10px;
            border-radius: 0 0 10px 10px;
        }

        .chat-input input {
            flex: 1;
            padding: 12px 20px;
            border: 1px solid #dee2e6;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
        }

        .chat-input button {
            padding: 12px 24px;
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            white-space: nowrap;
        }

        .message {
            margin-bottom: 20px;
        }

        .message-content {
            padding: 12px 16px;
            border-radius: 15px;
            max-width: 80%;
            word-wrap: break-word;
        }

        .user-message {
            display: flex;
            justify-content: flex-end;
        }

        .user-message .message-content {
            background: #007AFF;
            color: white;
            border-radius: 15px 15px 0 15px;
        }

        .bot-message .message-content {
            background: #f1f1f1;
            color: black;
            border-radius: 15px 15px 15px 0;
        }

        .session-list {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .session-item {
            padding: 10px;
            margin: 5px 0;
            background: rgba(255,255,255,0.1);
            border-radius: 5px;
            cursor: pointer;
        }

        .session-item:hover {
            background: rgba(255,255,255,0.2);
        }

        .session-item.active {
            background: #007AFF;
        }

        .new-session-btn {
            width: 100%;
            padding: 12px;
            background: #28a745;
            border: none;
            border-radius: 5px;
            color: white;
            cursor: pointer;
            margin-bottom: 20px;
        }

        .export-btn {
            width: 100%;
            padding: 12px;
            background: #6c757d;
            border: none;
            border-radius: 5px;
            color: white;
            cursor: pointer;
            margin-top: 10px;
        }

        .bot-message pre {
            background: #2d3748;
            border-radius: 8px;
            margin: 10px 0;
            padding: 15px;
            overflow-x: auto;
        }

        .mermaid {
            background: white;
            padding: 10px;
            border-radius: 8px;
            margin: 10px 0;
        }

        .typing-indicator {
            display: none;
            padding: 12px 16px;
            background: #f1f1f1;
            border-radius: 15px;
            margin-bottom: 20px;
            width: fit-content;
        }

        .typing-indicator span {
            display: inline-block;
            width: 8px;
            height: 8px;
            background: #666;
            border-radius: 50%;
            margin-right: 5px;
            animation: typing 1s infinite;
        }

        @keyframes typing {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-5px); }
        }

        .typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
        .typing-indicator span:nth-child(3) { animation-delay: 0.4s; }

        @media (max-width: 768px) {
            .sidebar {
                display: none;
            }
            .main-content {
                margin-left: 0;
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <button class="new-session-btn" onclick="createNewSession()">New Chat</button>
        <h3>Chat History</h3>
        <div id="sessionList" class="session-list"></div>
        <button class="export-btn" onclick="exportCurrentSession()">Export Current Chat</button>
    </div>
    
    <div class="main-content">
        <div class="chat-container">
            <div class="chat-header">
                <h2 style="margin: 0;">AI Assistant</h2>
                <div id="currentSessionInfo" style="font-size: 0.8em; margin-top: 5px;"></div>
            </div>
            <div class="chat-messages" id="chatMessages"></div>
            <div class="typing-indicator" id="typingIndicator">
                <span></span><span></span><span></span>
            </div>
            <div class="chat-input">
                <input type="text" id="messageInput" placeholder="Type your message here...">
                <button onclick="sendMessage()" id="sendButton">Send</button>
            </div>
        </div>
    </div>

    <script>
        const WEBHOOK_URL = 'http://172.21.217.52:5678/webhook/chat-webhook';
        let currentSessionId = null;
        let sessions = JSON.parse(localStorage.getItem('chatSessions')) || {};
        const messagesDiv = document.getElementById('chatMessages');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const typingIndicator = document.getElementById('typingIndicator');

        // Initialize mermaid
        mermaid.initialize({ startOnLoad: true });

        // Configure marked
        marked.setOptions({
            highlight: function(code, lang) {
                if (lang === 'mermaid') {
                    return `<div class="mermaid">${code}</div>`;
                }
                if (Prism.languages[lang]) {
                    return Prism.highlight(code, Prism.languages[lang], lang);
                }
                return code;
            },
            breaks: true,
            gfm: true
        });

        function createNewSession() {
            const sessionId = Date.now().toString();
            const session = {
                id: sessionId,
                name: `Chat ${Object.keys(sessions).length + 1}`,
                timestamp: new Date().toISOString(),
                messages: []
            };
            sessions[sessionId] = session;
            saveSessions();
            loadSession(sessionId);
            updateSessionList();
        }

        function updateSessionList() {
            const sessionList = document.getElementById('sessionList');
            sessionList.innerHTML = '';
            
            Object.values(sessions)
                .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
                .forEach(session => {
                    const div = document.createElement('div');
                    div.className = `session-item ${session.id === currentSessionId ? 'active' : ''}`;
                    div.onclick = () => loadSession(session.id);
                    
                    const messageCount = session.messages.length;
                    const date = new Date(session.timestamp).toLocaleDateString();
                    
                    div.innerHTML = `
                        <div>${session.name}</div>
                        <div class="session-info">${messageCount} messages • ${date}</div>
                    `;
                    sessionList.appendChild(div);
                });
        }

        function loadSession(sessionId) {
            currentSessionId = sessionId;
            const session = sessions[sessionId];
            messagesDiv.innerHTML = '';
            
            session.messages.forEach(msg => {
                addMessage(msg.content, msg.isUser, false);
            });
            
            updateSessionList();
            document.getElementById('currentSessionInfo').textContent = `Session: ${session.name}`;
        }

        function addMessage(message, isUser, save = true) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`;
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            
            if (isUser) {
                contentDiv.textContent = message;
            } else {
                contentDiv.innerHTML = marked.parse(message);
                // Initialize any new mermaid diagrams
                setTimeout(() => {
                    mermaid.init(undefined, contentDiv.querySelectorAll('.mermaid'));
                }, 100);
            }
            
            messageDiv.appendChild(contentDiv);
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;

            if (save && currentSessionId) {
                sessions[currentSessionId].messages.push({
                    content: message,
                    isUser: isUser,
                    timestamp: new Date().toISOString()
                });
                sessions[currentSessionId].timestamp = new Date().toISOString();
                saveSessions();
                updateSessionList();
            }
        }

        function saveSessions() {
            localStorage.setItem('chatSessions', JSON.stringify(sessions));
        }

        function exportCurrentSession() {
            if (!currentSessionId || !sessions[currentSessionId]) return;
            
            const session = sessions[currentSessionId];
            const exportData = {
                name: session.name,
                timestamp: session.timestamp,
                messages: session.messages
            };
            
            const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `chat-export-${session.name}-${new Date().toISOString()}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        async function sendMessage() {
            if (!currentSessionId) {
                createNewSession();
            }

            const message = messageInput.value.trim();
            if (!message) return;

            messageInput.disabled = true;
            sendButton.disabled = true;
            addMessage(message, true);
            messageInput.value = '';
            
            typingIndicator.style.display = 'block';
            
            try {
                const response = await fetch(WEBHOOK_URL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        message,
                        sessionId: currentSessionId
                    })
                });

                const data = await response.json();
                typingIndicator.style.display = 'none';
                addMessage(data.response || data.output, false);
            } catch (error) {
                console.error('Error:', error);
                typingIndicator.style.display = 'none';
                addMessage('Sorry, there was an error processing your message.', false);
            }

            messageInput.disabled = false;
            sendButton.disabled = false;
            messageInput.focus();
        }

        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // Initialize with a new session if none exists
        if (Object.keys(sessions).length === 0) {
            createNewSession();
        } else {
            // Load the most recent session
            const mostRecent = Object.values(sessions)
                .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))[0];
            loadSession(mostRecent.id);
        }
    </script>
</body>
</html>